import { ref } from 'vue';
import { getCurrentLocation as getLocation, getRegeo } from '@/utils/amapWx';
import type { LocationInfo } from '../types';

export function useLocation() {
  const currentLocation = ref('定位中...');
  const locationInfo = ref<LocationInfo | null>(null);

  // 获取定位
  const selectLocation = async () => {
    try {
      uni.showLoading({ title: '定位中...' });
      
      // 获取当前位置
      const location = await getLocation();
      
      // 逆地理编码获取地址信息
      const addressResult = await getRegeo(location);

      if (addressResult.success) {
        currentLocation.value = `${addressResult.city}${addressResult.district}`;
        
        // 保存位置信息
        locationInfo.value = {
          province: addressResult.province,
          city: addressResult.city,
          district: addressResult.district,
          latitude: location.latitude,
          longitude: location.longitude,
          fullAddress: addressResult.fullAddress
        };
        
        // 保存到本地存储
        uni.setStorageSync('userLocation', locationInfo.value);

        uni.hideLoading();
        uni.showToast({
          title: '定位成功',
          icon: 'success'
        });
      }
    } catch (error) {
      uni.hideLoading();
      console.error('定位失败:', error);
      uni.showToast({
        title: '定位失败，请检查定位权限',
        icon: 'none'
      });
      currentLocation.value = '定位失败,点击重试';
    }
  };

  // 从本地加载位置
  const loadSavedLocation = () => {
    const savedLocation = uni.getStorageSync('userLocation');
    if (savedLocation && savedLocation.city) {
      currentLocation.value = `${savedLocation.city}${savedLocation.district}`;
      locationInfo.value = savedLocation;
      return true;
    }
    return false;
  };

  return {
    currentLocation,
    locationInfo,
    selectLocation,
    loadSavedLocation
  };
}